/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * jdRegistrarRoles.java
 *
 * Created on 13-ago-2010, 12:08:14
 */

package GestionRoles;

import administracion.BeanBinding.TblBeanBindingFunciones;
import administracion.delegate.GestionSeguridadDelegate;
import administracion.helper.MiTablePrint;
import administracion.helper.Utiles_MensajesDialogo;
import administracion.helper.Utiles_Tabla;
import java.awt.Frame;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import org.jdesktop.beansbinding.AutoBinding;
import org.jdesktop.beansbinding.BindingGroup;
import org.jdesktop.beansbinding.ELProperty;
import org.jdesktop.swingbinding.JTableBinding;
import org.jdesktop.swingbinding.SwingBindings;
import seguridad.administracion.ejb30.entity.DetalleRolFuncion;
import seguridad.administracion.ejb30.entity.DetalleRolFuncionPK;
import seguridad.administracion.ejb30.entity.FuncionesRol;
import seguridad.administracion.ejb30.entity.FuncionesRolPK;
import seguridad.administracion.ejb30.entity.Roles;

/**
 *
 * @author Diana
 */
public class jdRegistrarRoles extends javax.swing.JDialog {
    List<TblBeanBindingFunciones> funciones;
    private BindingGroup bindingGroup;
    private JTableBinding jTableBinding;
    /** Creates new form jdRegistrarRoles */
    public jdRegistrarRoles(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        funciones= new ArrayList<TblBeanBindingFunciones>();
    }
    public void agregaDetalle(TblBeanBindingFunciones detalle) throws Exception {
    try {

      if (verificaNoExisteSuministro(detalle)) {
        this.funciones.add(detalle);
        actualizaTablaDetalle();
      } else {
         Utiles_MensajesDialogo.mensajeAlerta("LA FUNCION " + detalle.getDescripcion()+ "\n DEL SISTEMA "+ detalle.getSistema()+ "YA FUE SELECCIONADA");
      }
    } catch (Exception e) {
      throw e;
    }
  }
    private boolean verificaNoExisteSuministro(TblBeanBindingFunciones detalle) {
    boolean retorno = true;
    for (TblBeanBindingFunciones det : this.funciones) {
      if (det.getDescripcion().equalsIgnoreCase(detalle.getDescripcion()) && det.getSistema().equalsIgnoreCase(detalle.getSistema())) {
        retorno = false;
        break;
      }
    }
    return retorno;
  }
    public void actualizaTablaDetalle() {
        this.bindingGroup = new BindingGroup();
        this.jTableBinding = SwingBindings.createJTableBinding(AutoBinding.UpdateStrategy.READ, this.funciones, this.jtFunciones);

        JTableBinding.ColumnBinding columnBinding0 = this.jTableBinding.addColumnBinding(ELProperty.create("${sistema}"));

        columnBinding0.setColumnName("SISTEMA");
        columnBinding0.setColumnClass(String.class);
        columnBinding0.setEditable(false);

        JTableBinding.ColumnBinding columnBinding1 = this.jTableBinding.addColumnBinding(ELProperty.create("${descripcion}"));

        columnBinding1.setColumnName("DESCRIPCION");
        columnBinding1.setColumnClass(String.class);
        columnBinding1.setEditable(false);

    

        this.bindingGroup.addBinding(this.jTableBinding);
        this.bindingGroup.bind();


        int[] porcentajes= {30,70};
        try {
            Utiles_Tabla.definirAnchoColumnasJTable(this.jtFunciones, porcentajes);
        } catch (Exception ex) {
            Logger.getLogger(jdAdministrarFuncion.class.getName()).log(Level.SEVERE, null, ex);
        }
  }
    public Boolean registrarRoles(){
        Boolean estado=false;
        Calendar calendario = new GregorianCalendar();
       // Date fecha= Calendar.get
        Roles rol= new Roles();
        rol.setDescripcionRol(this.jtfRoles.getText());
        List<DetalleRolFuncion> funciroles= new ArrayList<DetalleRolFuncion>();
        for(TblBeanBindingFunciones deta: this.funciones){
           DetalleRolFuncionPK fun_rolPK= new DetalleRolFuncionPK (0, deta.getCodFuncion(), deta.getCodsistema());
           DetalleRolFuncion fun_rol= new DetalleRolFuncion();
           fun_rol.setDetalleRolFuncionPK(fun_rolPK);
           fun_rol.setFechaOperacion(new Date());
           funciroles.add(fun_rol);
       }
        try {
           estado= GestionSeguridadDelegate.getInstance().insertarfuncionRol(funciroles, rol);
        } catch (Exception ex) {
            Logger.getLogger(jdRegistrarRoles.class.getName()).log(Level.SEVERE, null, ex);
        }
        return estado;
    }
    private void eliminarFila() {

        String non_fun = this.jtFunciones.getValueAt(this.jtFunciones.getSelectedRow(), 1).toString().trim();
        String nom_sis = this.jtFunciones.getValueAt(this.jtFunciones.getSelectedRow(), 0).toString().trim();

        for (TblBeanBindingFunciones det : this.funciones) {
          if (det.getDescripcion().equalsIgnoreCase(non_fun) && det.getSistema().equalsIgnoreCase(nom_sis)) {
            this.funciones.remove(det);
            break;
          }
        }
        actualizaTablaDetalle();
      }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jtfRoles = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtFunciones = new javax.swing.JTable();
        jbtAgregar = new javax.swing.JButton();
        jbtEliminar = new javax.swing.JButton();
        jbCancelar = new javax.swing.JButton();
        jbAceptar = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setName("Form"); // NOI18N

        jtfRoles.setName("jtfRoles"); // NOI18N

        jLabel1.setName("jLabel1"); // NOI18N

        jPanel1.setName("jPanel1"); // NOI18N

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        jtFunciones.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "DESCRIPCION DE FUNCION"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jtFunciones.setName("jtFunciones"); // NOI18N
        jScrollPane2.setViewportView(jtFunciones);

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(gestionseguridadadministrativacliente.GestionSeguridadAdministrativaclienteApp.class).getContext().getResourceMap(jdRegistrarRoles.class);
        jbtAgregar.setFont(resourceMap.getFont("jbtAgregar.font")); // NOI18N
        jbtAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconoscomb/16x16ozygen/actions/list_add.png"))); // NOI18N
        jbtAgregar.setMnemonic('A');
        jbtAgregar.setText(resourceMap.getString("jbtAgregar.text")); // NOI18N
        jbtAgregar.setName("jbtAgregar"); // NOI18N
        jbtAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtAgregarActionPerformed(evt);
            }
        });

        jbtEliminar.setFont(resourceMap.getFont("jbtEliminar.font")); // NOI18N
        jbtEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconoscomb/16x16ozygen/actions/list_remove.png"))); // NOI18N
        jbtEliminar.setMnemonic('E');
        jbtEliminar.setText(resourceMap.getString("jbtEliminar.text")); // NOI18N
        jbtEliminar.setName("jbtEliminar"); // NOI18N
        jbtEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtEliminarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 525, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jbtAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbtEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jbtAgregar, jbtEliminar});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 312, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jbtAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbtEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jbCancelar.setFont(resourceMap.getFont("jbCancelar.font")); // NOI18N
        jbCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconoscomb/16x16ozygen/actions/button_cancel.png"))); // NOI18N
        jbCancelar.setMnemonic('C');
        jbCancelar.setText(resourceMap.getString("jbCancelar.text")); // NOI18N
        jbCancelar.setName("jbCancelar"); // NOI18N
        jbCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbCancelarActionPerformed(evt);
            }
        });

        jbAceptar.setFont(resourceMap.getFont("jbAceptar.font")); // NOI18N
        jbAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconoscomb/16x16ozygen/actions/apply.png"))); // NOI18N
        jbAceptar.setMnemonic('A');
        jbAceptar.setText(resourceMap.getString("jbAceptar.text")); // NOI18N
        jbAceptar.setName("jbAceptar"); // NOI18N
        jbAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbAceptarActionPerformed(evt);
            }
        });

        jLabel2.setFont(resourceMap.getFont("jLabel2.font")); // NOI18N
        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel2)
                        .addGap(20, 20, 20)
                        .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jtfRoles, javax.swing.GroupLayout.PREFERRED_SIZE, 393, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(130, 130, 130))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap(426, Short.MAX_VALUE)
                        .addComponent(jbAceptar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbCancelar))
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 662, Short.MAX_VALUE))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jbAceptar, jbCancelar});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(jtfRoles, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbCancelar)
                    .addComponent(jbAceptar))
                .addContainerGap(12, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jbCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbCancelarActionPerformed

        this.dispose();
}//GEN-LAST:event_jbCancelarActionPerformed

    private void jbAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAceptarActionPerformed
         if (Utiles_MensajesDialogo.mensajeConfirmacion("Esta seguro de registrar el rol?")){
            if(registrarRoles()){
                Utiles_MensajesDialogo.mensajeExito();
            }
        }
         this.jtfRoles.setText("");
         this.funciones.clear();
         this.actualizaTablaDetalle();

    }//GEN-LAST:event_jbAceptarActionPerformed

    private void jbtAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtAgregarActionPerformed
        jdRegistrarFuncion jdAgregaDetalle=new jdRegistrarFuncion(null,true, this);
            jdAgregaDetalle.setLocationRelativeTo(null);
            jdAgregaDetalle.setVisible(true);
    }//GEN-LAST:event_jbtAgregarActionPerformed

    private void jbtEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtEliminarActionPerformed
           try {
            if (this.jtFunciones.getSelectedRow() < 0) {
                Utiles_MensajesDialogo.mensajeError("Debe elegir un detalle");
                return;
            }
            if (Utiles_MensajesDialogo.mensajeConfirmacion("Esta seguro de eliminar el detalle?"))
                eliminarFila();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_jbtEliminarActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                jdRegistrarRoles dialog = new jdRegistrarRoles(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton jbAceptar;
    private javax.swing.JButton jbCancelar;
    private javax.swing.JButton jbtAgregar;
    private javax.swing.JButton jbtEliminar;
    public javax.swing.JTable jtFunciones;
    private javax.swing.JTextField jtfRoles;
    // End of variables declaration//GEN-END:variables

}
